package com.fms.fmsapi.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fms.fmsapi.entity.R;
import com.fms.fmsapi.entity.Role;
import com.fms.fmsapi.entity.User;
import com.fms.fmsapi.entity.result.UserResult;
import com.fms.fmsapi.service.UserService;
import com.fms.fmsapi.service.impl.RoleServiceImpl;
import com.fms.fmsapi.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张力文
 * @since 2024-04-04
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RoleServiceImpl roleService;
    @GetMapping
    public R list(String keyword)
    {
        List<UserResult> list = userService.list(keyword);
        return R.success(list);
    }

    @GetMapping("/delete")
    public R delete(String uuid){
        boolean flag = userService.removeById(uuid);
        return flag ? R.success("删除成功") : R.success("删除失败");
    }

    @PostMapping("/edit")
    public R edit(@RequestBody User user){
        System.out.println(user);
        boolean flag = userService.updateById(user);
        return flag ? R.success("修改成功") : R.success("修改失败");
    }
    @GetMapping("/getInfo")
    public R getInfo(String uuid){
        User user = userService.getById(uuid);
        Role role = roleService.getById(user.getRoleId());
        UserResult userResult = new UserResult();
        BeanUtils.copyProperties(user,userResult);
        if(role!=null){
            userResult.setRoleName(role.getName());
        } else{
            userResult.setRoleName("暂无角色");
        }
        return R.success(userResult);
    }

    @GetMapping("/getSelfInfo")
    public UserResult getSelfUuid(HttpServletRequest request){
        String token = JwtUtil.getToken(request);
        String userId = JwtUtil.getUserId(token);
        User user = userService.getById(userId);
        UserResult userResult = new UserResult();
        BeanUtils.copyProperties(user,userResult);
        Role role = roleService.getById(user.getRoleId());
        userResult.setRoleName(role!=null?role.getName():"暂无角色");
        return userResult;
    }
}

